<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input
        @clear="doSearch"
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.name"
      />
      <el-button @click="doSearch" type="primary">查询</el-button>
      <el-button @click="exportExcel">导出Excel</el-button>
    </div>
    <auth-btn btnPerm="park:building:add_edit">
      <el-button type="primary" @click="openBuilding">添加楼宇</el-button>
    </auth-btn>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="buildingList">
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="楼宇名称" width="180" prop="name" />
        <el-table-column label="层数" prop="floors" />
        <el-table-column label="在管面积(m²)" width="120" prop="area" />
        <el-table-column label="物业费(元/m²)" width="120" prop="propertyFeePrice" />
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <auth-btn btnPerm="park:building:add_edit">
              <el-button size="mini" type="text" @click="editBuilding(scope.row.id)">编辑</el-button>
            </auth-btn>
            <auth-btn btnPerm="park:building:remove">
              <el-button size="mini" type="text" @click="delBuilding(scope.row.id)">删除</el-button>
            </auth-btn>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="sizeChange"
        @current-change="pageChange"
      />
    </div>
    <!-- 添加楼宇弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="addForm.id ? '编辑楼宇' : '添加楼宇'"
      :visible="dialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form :model="addForm" :rules="addFormRules" ref="addForm">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model.number="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model.number="addForm.area">
              <template slot="append">m²</template>
            </el-input>
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model.number="addForm.propertyFeePrice">
              <template slot="append">元/m²</template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBuildingListAPI,
  createBuildingAPI,
  delBuildingAPI,
  editBuildingAPI,
  getBuildingDetailAPI,
} from "@/api/building";
import { utils, writeFileXLSX } from "xlsx";
export default {
  name: "Building",
  data() {
    return {
      buildingList: [], // table列表
      params: {
        // 请求参数
        page: 1,
        pageSize: 10,
        name: "",
      },
      total: 0,
      dialogVisible: false,
      addForm: {
        name: "",
        floors: null,
        area: null,
        propertyFeePrice: null,
      },
      addFormRules: {
        name: [{ required: true, message: "请输入楼宇名称", trigger: "blur" }],
        floors: [{ required: true, message: "请输入楼宇层数", trigger: "blur" }],
        area: [{ required: true, message: "请输入楼宇面积", trigger: "blur" }],
        propertyFeePrice: [{ required: true, message: "请输入楼宇物业费", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getBuildingList();
  },
  computed: {
    statusMap() {
      return {
        0: "租赁中",
        1: "闲置中",
      };
    },
  },
  methods: {
    // 格式化状态字段
    formatStatus(status) {
      return this.statusMap[status] || "未知状态";
    },
    // 导出excel
    exportExcel() {
      // 导出字段key/字段排序
      const tableHeaderKeys = ["name", "floors", "area", "propertyFeePrice", "status"];
      // 表头中文字段value
      const tableHeaderValues = ["楼宇名称", "层数", "在管面积(㎡)", "物业费(㎡)", "状态"];
      // 筛选需要导出的字段  list:[{ 需要的key:item[key]的value }, {}, ...]
      const list = this.buildingList.map((item) => {
        const obj = {};
        // 遍历需要键名/排序（注意forEach有序，提前在tableHeaderKeys中排序）
        tableHeaderKeys.forEach((key) => {
          // obj中的 键:值 = item中的 键:值
          if (key === "status") {
            obj[key] = this.statusMap[item[key]];
          } else {
            obj[key] = item[key];
          }
        });
        // 每次遍历返回一个对象
        return obj;
      });
      // 创建一个新的工作簿
      const workbook = utils.book_new();
      // 创建一个工作表 要求一个对象数组格式
      const worksheet = utils.json_to_sheet(list);
      // 把工作表添加到工作簿  Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, "Data");
      // 改写表头
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: "A1" });
      // 导出方法进行导出
      writeFileXLSX(workbook, "楼宇列表.xlsx");
    },
    // 编辑楼宇
    async editBuilding(id) {
      this.addForm = (await getBuildingDetailAPI(id)).data;
      this.openBuilding();
    },
    // 删除楼宇
    async delBuilding(id) {
      this.$confirm("确认删除当前楼宇吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await delBuildingAPI(id);
          this.$message({
            type: "success",
            message: "直到大厦崩塌~",
          });
          this.getBuildingList();
        })
        .catch(() => {});
    },
    // 提交添加表单
    confirmAdd() {
      this.$refs.addForm.validate(async (flag) => {
        if (!flag) return;
        if (this.addForm.id) {
          delete this.addForm.status;
          delete this.addForm.delFlag;
          await editBuildingAPI(this.addForm);
        } else {
          await createBuildingAPI(this.addForm);
        }
        this.$message.success(this.addForm.id ? "编辑成功" : "哇！平地起高楼");
        this.closeDialog();
        this.getBuildingList();
      });
    },
    // 获取列表
    async getBuildingList() {
      const {
        data: { rows, total },
      } = await getBuildingListAPI(this.params);
      this.buildingList = rows;
      this.total = total;
      const maxPage = Math.ceil(total / this.params.pageSize);
      if (this.params.page > maxPage && maxPage > 0) {
        this.params.page = maxPage;
        this.$message.warning("已自动跳转到最后一页");
        this.getCardList();
        return;
      }
    },
    // 计算序号
    indexMethod(index) {
      return index + 1 + this.params.pageSize * (this.params.page - 1);
    },
    // 翻页
    pageChange(page) {
      this.params.page = page;
      this.getBuildingList();
    },
    // 修改页容量
    sizeChange(val) {
      this.params.pageSize = val;
      this.getBuildingList();
    },
    // 查询
    doSearch() {
      // 1. 重置page为1
      this.params.page = 1;
      // 2. 调用获取列表接口
      this.getBuildingList();
    },
    // 打开添加弹框
    openBuilding() {
      this.dialogVisible = true;
    },
    // 关闭添加弹框
    closeDialog() {
      this.addForm = {
        name: "",
        floors: null,
        area: null,
        propertyFeePrice: null,
      };
      this.$refs.addForm.resetFields();
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}
.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;
  .search-label {
    width: 100px;
  }
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
</style>
